<?php 
namespace Emos\Field;

use Emos\Common;

class DateTime extends AbstractControl {
    public function __construct() {        
    }
    
    public function html() {
        $date = '';    
        $time = '';    
        if($v = $this->parseDbString($this->value)) {                            
            $date = "{$v['day']}.{$v['month']}.{$v['year']}"; 
            $time = "{$v['hour']}:{$v['minute']}";
        }
        
        return 
            "<input type='text' class='datepicker' data-format='dd.mm.yy' name='{$this->htmlName}[date]' value='".Common::plain($date)."' /> ".
            "<input type='text' class='time' name='{$this->htmlName}[time]' value='".Common::plain($time)."' />";
    }
    
    public function update() {
        $p = $this->getPost();
        if($p === null) {
            return array($this->dbName => new Db\SqlExpression("NULL"));        
        }
        else {            
            if(($d = $this->parseDateInputString($p['date'])) && ($t = $this->parseTimeInputString($p['time']))) {                 
                return array($this->dbName => "{$d['year']}-{$d['month']}-{$d['day']} {$t['hour']}:{$t['minute']}:00");        
            }            
        }
    }  
    
    public function validate() {     
        $p = $this->getPost();
        if($p === null && $this->nullable) {
            return;
        }
        elseif(($d = $this->parseDateInputString($p['date'])) && ($t = $this->parseTimeInputString($p['time']))) {                            
            if(
                $d['day']    >= 1  &&  $d['day']    <= 31 &&
                $d['month']  >= 1  &&  $d['month']  <= 12 && 
                $d['year']   >= 1  &&  $d['year']   <= 9999 &&
                    
                $t['hour']   >= 0  &&  $t['hour']   < 24 &&
                $t['minute'] >= 0  &&  $t['minute'] < 60                     
            ) {
                return; 
            }
        }       
        
        $this->error = true;                        
    }
    
    public function getDdlFields() {
        return array(
            $this->dbName => "DATETIME"
        );
    }   
    
    protected function parseDbString($str) {
        if(preg_match('/^  (?<year> \d+) \- (?<month> \d+) \- (?<day> \d+)    \s+    (?<hour> \d+) : (?<minute> \d+) /xui', $str, $m)) {                            
            return $m;
        }
        return null;
    }
    
    protected function parseDateInputString($str) {
        if(preg_match('/^ (?<day> \d+) \. (?<month> \d+) \. (?<year> \d+) $/xui', $str, $m)) {                            
            return $m;
        }
        return null;
    }    
    
    protected function parseTimeInputString($str) {
        if(preg_match('/^ (?<hour> \d+) : (?<minute> \d+)   (:\d+)?  $/xui', $str, $m)) {                            
            return $m;
        }
        return null;
    }     
}